package com.oauth.service.google.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oauth.service.OAuthDAO;
import com.oauth.service.google.beans.GoogleYouTubeBean;
import com.oauth.service.google.constants.GoogleState;
import com.oauth.service.jdosupport.PMF;
import com.oauth.service.linkedin.constants.LinkedinState;

public class GoogleYouTubeDaoImpl implements OAuthDAO<GoogleYouTubeBean> {

	@Override
	public void deleteToken(Long pMemberId) {
		GoogleYouTubeBean serviceBean = getToken(pMemberId);

		if (serviceBean != null) {

			serviceBean.setState(GoogleState.DELETED);
			PersistenceManager persistenceManager = PMF.get()
					.getPersistenceManager();
			try {
				persistenceManager.makePersistent(serviceBean);
			} finally {
				persistenceManager.close();
			}
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public GoogleYouTubeBean getToken(Long pMemberId) {
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();

		Query query = persistenceManager.newQuery(GoogleYouTubeBean.class,
				"memberId == " + pMemberId + " && state == stateParam");

		query.declareParameters("int stateParam");
		List<GoogleYouTubeBean> results;
		results = (List<GoogleYouTubeBean>) query.execute(LinkedinState.ACTIVE
				.getState());

		if (results != null && !results.isEmpty()) {
			return results.get(0);
		}
		return null;
	}

	@Override
	public GoogleYouTubeBean persistToken(GoogleYouTubeBean pServiceBean) {

		GoogleYouTubeBean serviceBean = getToken(pServiceBean.getMemberId());

		if (serviceBean != null) {
			//Update key so that it will update existing object instead of creating new one.
			pServiceBean.setKey(serviceBean.getKey()); 
		}
		// default set to active.
		pServiceBean.setState(GoogleState.ACTIVE);
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		try {
			pServiceBean = persistenceManager.makePersistent(pServiceBean);
		} finally {
			persistenceManager.close();
		}
		return pServiceBean;
	}

}
